// 生成一个随机的 5×5 矩阵
function generateRandomMatrix(size: number): number[][] {
    const matrix: number[][] = [];
    for (let i = 0; i < size; i++) {
        matrix.push([]);
        for (let j = 0; j < size; j++) {
            // @ts-ignore
            matrix[i].push((Math.random() * 10 - 5).toFixed(2)); // 生成 -5 到 5 之间的随机数
        }
    }
    return matrix;
}

// 计算矩阵的行列式（仅适用于 5×5 矩阵）
function determinant(matrix: number[][]): number {
    if (matrix.length !== matrix[0].length) {
        throw new Error("Matrix must be square");
    }
    const size = matrix.length;
    if (size === 1) return matrix[0][0];
    if (size === 2)
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];

    let det = 0;
    for (let i = 0; i < size; i++) {
        const subMatrix: number[][] = [];
        for (let j = 1; j < size; j++) {
            const row: number[] = [];
            for (let k = 0; k < size; k++) {
                if (k !== i) row.push(matrix[j][k]);
            }
            subMatrix.push(row);
        }
        det += matrix[0][i] * Math.pow(-1, i) * determinant(subMatrix);
    }
    return det;
}

// 生成一个随机的解向量
function generateRandomSolutionVector(size: number): number[] {
    const vector: number[] = [];
    for (let i = 0; i < size; i++) {
        vector.push((Math.random() * 10 - 5).toFixed(2)); // 生成 -5 到 5 之间的随机数
    }
    return vector;
}

// 计算常数项向量 B = A * X
function multiplyMatrixVector(matrix: number[][], vector: number[]): number[] {
    const result: number[] = [];
    for (let i = 0; i < matrix.length; i++) {
        let sum = 0;
        for (let j = 0; j < vector.length; j++) {
            sum += matrix[i][j] * vector[j];
        }
        result.push(sum.toFixed(2));
    }
    return result;
}

// 生成一个有实数解的 5 元一次方程组
function generateSolvableEquations(size: number): {
    equations: string;
    solution: number[];
    matrix: number[][];
    constants: number[];
} {
    let matrix: number[][];
    let solutionVector: number[];
    let constants: number[];

    do {
        matrix = generateRandomMatrix(size);
        solutionVector = generateRandomSolutionVector(size);
        constants = multiplyMatrixVector(matrix, solutionVector);
    } while (determinant(matrix) === 0); // 确保矩阵可逆

    const equations: string[] = [];
    for (let i = 0; i < size; i++) {
        let equation = "";
        for (let j = 0; j < size; j++) {
            equation += matrix[i][j] + "x" + (j + 1) + " + ";
        }
        equation = equation.slice(0, -3) + " = " + constants[i];
        equations.push(equation);
    }

    return {
        equations: equations.join("\n"),
        solution: solutionVector,
        matrix: matrix,
        constants: constants,
    };
}

// 生成方程组
//   const result = generateSolvableEquations(5);
//   console.log("方程组：");
//   console.log(result.equations);
//   console.log("解向量：");
//   console.log(result.solution);
